/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2020年9月2日
 */
package com.massyframework.beanskin.launcher.deploying;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.massyframework.beanskin.ModuleIdentifier;
import com.massyframework.beanskin.ModuleJarsLocator;
import com.massyframework.beanskin.util.localstore.LocalStore;


/**
 * 缺省的模块URL定位器
 * 
 * @author huangkh
 *
 */
class DefaultModuleURLLocator implements ModuleJarsLocator{
	
	private Logger logger = LoggerFactory.getLogger(DefaultModuleURLLocator.class);
	private LocalStore localStore;

	/**
	 * 
	 */
	public DefaultModuleURLLocator(LocalStore localStore) {
		this.localStore = Objects.requireNonNull(localStore, "\"localStore\" cannot be null.");
	}

	/**
	 * 定位模块位置
	 * @param module {@link ModuleIdentifier}, 模块标识符
	 * @return {@link List}
	 */
	public List<URL> locate(ModuleIdentifier module) {
		Path path =  this.localStore.getDeploymentDirectory(module).resolve("lib");
		File dir = path.toFile();
		if (!dir.exists()) {
			return Collections.emptyList();
		}
		
		List<URL> result = new ArrayList<>();
		if (dir.isDirectory()) {
			this.listFileWithJar(dir, result, true);
		}
		return result;
	}
	
	/**
	 * 列出{@link dir}中的jar文件
	 * @param dir {@link File},目录
	 * @param jarUrls {@link List}, jar文件的URL地址
	 * @param containOsDir {@link boolean},是否包含os目录
	 */
	protected void listFileWithJar(File dir, List<URL> jarUrls, boolean containOsDir) {
		File[] files = dir.listFiles();
		if (files != null) {
			for (File file: files) {
				if (file.isFile()) { 
					if (file.getName().endsWith(".jar")) {
						try {
							jarUrls.add(file.toURI().toURL());
						}catch(IOException e) {
							if (logger.isErrorEnabled()) {
								logger.error(e.getMessage(), e);
							}
						}
					}
				}else {
					if (containOsDir) {
						if (file.getName().equals(OsNameUtils.getOsName())) {
							listFileWithJar(file, jarUrls, false);
						}
					}
				}
			}
		}
	}
}
